const jwt = require('jsonwebtoken');
const errorTypes = require('../constants/error-types');
const userService = require('../service/user.service');
const authService = require('../service/auth.service')
const md5password = require('../utils/password-handle');
const { PUBLIC_KEY } = require('../app/config')

const verifyLogin = async (ctx, next) => {
    //获取手机号和密码
    const { name, password } = ctx.request.body;

    //判断用户名和密码是否为空
    if (!name || !password || name === '' || password === '') {
        const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
        return ctx.app.emit('error', error, ctx);
    }

    //判断用户是否存在
    const result = await userService.getUserByName(name);
    const user = result[0];
    if (!user) {
        const error = new Error(errorTypes.USER_DOES_NOT_EXISTS);
        return ctx.app.emit('error', error, ctx);
    }

    //判断密码是否正确
    if (md5password(password) !== user.password) {
        const error = new Error(errorTypes.PASSWORD_IS_INCORRECT);
        return ctx.app.emit('error', error, ctx);
    }

    ctx.user = user;
    await next();
}

const verifyAuth = async (ctx, next) => {
    console.log("验证授权");

    // 获取token
    const authorization = ctx.headers.authorization;

    if (!authorization) {
        const err = new Error(errorTypes.NO_AUTHORIZATION);
        return ctx.app.emit("error", err, ctx);
    }
    const token = authorization.replace('Bearer ', '');


    // 验证token
    try {
        const result = jwt.verify(token, PUBLIC_KEY, {
            algorithms: ['RS256']
        });
        ctx.user = result;
        await next();
    } catch (err) {
        //这里也会捕获next里的错误信息
        const error = new Error(errorTypes.NO_AUTHORIZATION)
        ctx.app.emit('error', error, ctx);
    }

}
const verifyPermission = async (ctx, next) => {
    console.log("验证权限的verifyPermission");

    //获取参数
    const [resourceKey] = Object.keys(ctx.params);
    const tableName = resourceKey.replace('Id', '');
    const resourceId = ctx.params[resourceKey];
    const { id } = ctx.user;

    try {
        //查询是否具备权限
        const isPermission = await authService.checkResource(tableName, resourceId, id);

        if (!isPermission) {
            const error = new Error(errorTypes.NO_PERMISSION);
            return ctx.app.emit('error', error, ctx);
        }
        await next();
    } catch (err) {
        const error = new Error(errorTypes.NO_PERMISSION);
        return ctx.app.emit('error', error, ctx);
    }
}

// const verifyPermission = (tableName) => {
//     return async (ctx, next) => {
//         console.log("验证权限的verifyPermission");

//         //获取参数
//         const { momentId } = ctx.params;
//         const { id } = ctx.user;

//         try {
//             //查询是否具备权限
//             const isPermission = await authService.checkResource(tableName, momentId, id);

//             if (!isPermission) {
//                 const error = new Error(errorTypes.NO_PERMISSION);
//                 return ctx.app.emit('error', error, ctx);
//             }
//             await next();
//         } catch (err) {
//             const error = new Error(errorTypes.NO_PERMISSION);
//             return ctx.app.emit('error', error, ctx);
//         }
//     }
// }

module.exports = {
    verifyLogin,
    verifyAuth,
    verifyPermission
}